const express = require('express');
// 创建路由
const router = express.Router();

// mongodb Data模型
const Data = require('../models/Data')

// passport
const passport = require('passport');

/**
 * @route POST /api/data/add
 * @desc 数据添加
 * @access private
 */
router.post('/add', passport.authenticate("jwt", { session: false }), (req, res) => {
  Data.create({
      content: req.body.content = req.body.content ? req.body.content : '',
      income: req.body.income = req.body.income ? req.body.income : '',
      expend: req.body.expend = req.body.expend ? req.body.expend : '',
      remark: req.body.remark = req.body.remark ? req.body.remark : '',
    })
    .then(data => res.json({ message: '数据添加成功' }))
})

/**
 * @route GET /api/data
 * @desc 查询所有数据
 * @access private
 */
router.get('/', passport.authenticate("jwt", { session: false }), (req, res) => {
  Data.find()
    .then(data => res.json(data))
    .catch(err => res.json({ message: '没有找到数据' }))
})

/**
 * @route GET /api/data/:id
 * @desc 查询单个数据
 * @access private
 */
router.get('/:id', passport.authenticate("jwt", { session: false }), (req, res) => {
  Data.findOne({ _id: req.params.id })
    .then(data => res.json(data))
    .catch(err => res.json({ message: '没有找到该数据' }))
})


/**
 * @route DELETE /api/data/delete/:id
 * @desc 数据删除
 * @access private
 */
router.delete('/delete/:id', passport.authenticate("jwt", { session: false }), (req, res) => {
  Data.deleteOne({ _id: req.params.id })
    .then(result => res.json({ message: '删除成功' }))
    .catch(err => res.json({ message: '找不到该数据，无法删除' }))
})


/**
 * @route PUT /api/data/update/:id
 * @desc 数据修改
 * @access private
 */
router.put('/update/:id', passport.authenticate("jwt", { session: false }), (req, res) => {
  let updateData = {
    content: req.body.content = req.body.content ? req.body.content : '',
    income: req.body.income = req.body.income ? req.body.income : '',
    expend: req.body.expend = req.body.expend ? req.body.expend : '',
    remark: req.body.remark = req.body.remark ? req.body.remark : '',
    date: Date.now()
  }
  Data.updateOne({ _id: req.params.id }, { $set: updateData })
    .then(result => res.json({ message: '修改成功' }))
    .catch(err => res.json({ message: '找不到该数据，无法修改' }))
})




module.exports = router;